document.addEventListener('DOMContentLoaded', function() {
    // 自动填充保存的API密钥
    const savedApiKey = localStorage.getItem('bizyair_api_key');
    if (savedApiKey) { document.getElementById('api_key').value = savedApiKey; }
    
    // 初始化滑块显示
    const floatSlider = document.getElementById('float_value');
    if (floatSlider) {
        const floatDisplay = document.getElementById('float_value_display');
        floatSlider.addEventListener('input', function() { floatDisplay.textContent = this.value; });
    }
    
    // 初始化侧边栏状态
    const sidebarState = localStorage.getItem('sidebar_state');
    if (sidebarState === 'collapsed') { collapseSidebar(); }
    
    // 侧边栏切换按钮事件
    document.getElementById('toggleSidebar').addEventListener('click', toggleSidebar);
    document.getElementById('sidebarToggleBtn').addEventListener('click', toggleSidebar);

    // 根据JSON配置更新表单字段
    updateFormFields();

    // 初始化配置开关功能
    initConfigToggle();

    // 初始化CSV提示词选择功能
    initPromptSelector();
});

// 根据当前选择的模型（从PHP传入）更新表单 - 动态JSON识别模式
function updateFormFields() {
    const currentConfigData = window.currentConfigData || {};
    if (!currentConfigData || !currentConfigData.input_values) return;

    console.log('正在处理配置数据:', currentConfigData);
    console.log('输入值:', currentConfigData.input_values);

    // 按优先级顺序定义文本提示词格式 - 动态JSON识别
    const textPromptPatterns = [
        { pattern: /TextEncodeQwenImageEditPlus\.prompt/i, format: 'TextEncodeQwenImageEditPlus.prompt' },
        { pattern: /TextEncodeQwenImageEdit\.prompt/i, format: 'TextEncodeQwenImageEdit.prompt' },
        { pattern: /PrimitiveStringMultiline\.value/i, format: 'PrimitiveStringMultiline.value' },
        { pattern: /Text\s+Multiline\.text/i, format: 'Text Multiline.text' },
        { pattern: /CLIPTextEncode\.text/i, format: 'Text Multiline.text' },
        { pattern: /\.prompt$/i, format: 'generic.prompt' },
        { pattern: /\.text$/i, format: 'generic.text' },
        { pattern: /\.value$/i, format: 'generic.value' }
    ];

    let recognizedTextPrompt = null;
    let processedFields = new Set();
    let resolutionField = null;
    let resolutionValue = null;
    let sizeField = null;
    let sizeValue = null;
    let intFields = []; // 存储所有整数字段

    // 动态识别文本提示词格式
    for (const [key, value] of Object.entries(currentConfigData.input_values)) {
        // 跳过图片URL和纯数值参数
        if (!value || typeof value !== 'string') continue;
        if (value.startsWith('http') || value.startsWith('data:image')) continue;

        // 检查是否为数值字符串但排除可能是文本的情况
        if (isNumeric(value) && parseFloat(value).toString() === value.trim()) continue;

        // 检查是否为分辨率字段 (SDXLEmptyLatentSizePicker+.resolution)
        if (key.includes('SDXLEmptyLatentSizePicker+.resolution') && typeof value === 'string' && value.includes('x')) {
            resolutionField = key;
            resolutionValue = value;
            processedFields.add(key);
            console.log(`识别到分辨率字段: ${key} = ${value}`);
            continue;
        }
        
        // 检查是否为尺寸字段 (BizyAir_Seedream4.size)
        if (key.includes('BizyAir_Seedream4.size') && typeof value === 'string') {
            sizeField = key;
            sizeValue = value;
            processedFields.add(key);
            console.log(`识别到尺寸字段: ${key} = ${value}`);
            continue;
        }

        // 按优先级匹配不同的提示词格式
        for (const {pattern, format} of textPromptPatterns) {
            if (pattern.test(key)) {
                recognizedTextPrompt = {
                    field: key,
                    value: value,
                    format: format
                };
                processedFields.add(key);
                console.log(`识别到文本提示词格式: ${format} = ${value}`);
                break;
            }
        }

        if (recognizedTextPrompt) break; // 找到第一个匹配的文本提示词就停止
    }

    // 收集所有整数参数
    for (const [key, value] of Object.entries(currentConfigData.input_values)) {
        // 跳过已处理的字段
        if (processedFields.has(key)) continue;

        // 处理整数参数
        if (isNumeric(value) && !key.includes('scale_by') && !key.includes('float') && !key.includes('seed')) {
            intFields.push({
                key: key,
                value: parseInt(value)
            });
            processedFields.add(key);
            console.log(`识别到整数参数: ${key} = ${value}`);
        }
    }

    // 应用识别到的文本提示词
    if (recognizedTextPrompt) {
        const textPromptElement = document.getElementById('text_prompt');
        const textPromptFieldElement = document.getElementById('text_prompt_field');

        if (textPromptElement) {
            textPromptElement.value = recognizedTextPrompt.value;
        }

        if (textPromptFieldElement) {
            // 提取字段映射编号和格式
            const fieldNumber = recognizedTextPrompt.field.split(':')[0] || '';
            const fieldName = recognizedTextPrompt.format;
            textPromptFieldElement.value = fieldNumber ? `${fieldNumber}:${fieldName}` : fieldName;
        }

        console.log('已应用文本提示词:', recognizedTextPrompt);
    }

    // 处理分辨率字段
    if (resolutionField && resolutionValue) {
        const resolutionGroupElement = document.getElementById('resolution_group');
        const resolutionValueElement = document.getElementById('resolution_value');
        const resolutionFieldElement = document.getElementById('resolution_field');

        if (resolutionGroupElement) {
            resolutionGroupElement.style.display = 'block';
        }

        if (resolutionValueElement) {
            // 查找匹配的选项
            for (let i = 0; i < resolutionValueElement.options.length; i++) {
                if (resolutionValueElement.options[i].value === resolutionValue) {
                    resolutionValueElement.selectedIndex = i;
                    break;
                }
            }
        }

        if (resolutionFieldElement) {
            resolutionFieldElement.value = resolutionField;
        }

        console.log('已应用分辨率字段:', resolutionField, resolutionValue);
    }
    
    // 处理尺寸字段
    if (sizeField && sizeValue) {
        const sizeGroupElement = document.getElementById('size_group');
        const sizeValueElement = document.getElementById('size_value');
        const sizeFieldElement = document.getElementById('size_field');

        if (sizeGroupElement) {
            sizeGroupElement.style.display = 'block';
        }

        if (sizeValueElement) {
            // 查找匹配的选项
            for (let i = 0; i < sizeValueElement.options.length; i++) {
                if (sizeValueElement.options[i].value === sizeValue) {
                    sizeValueElement.selectedIndex = i;
                    break;
                }
            }
        }

        if (sizeFieldElement) {
            sizeFieldElement.value = sizeField;
        }

        console.log('已应用尺寸字段:', sizeField, sizeValue);
    }

    // 处理多个整数参数
    if (intFields.length > 0) {
        // 隐藏旧的单个整数参数组
        const oldIntGroup = document.getElementById('int_group');
        if (oldIntGroup) {
            oldIntGroup.style.display = 'none';
        }
        
        // 显示新的多个整数参数组
        intFields.forEach((intField, index) => {
            const intGroupElement = document.getElementById(`int_group_${index}`);
            const intElement = document.getElementById(`int_value_${index}`);
            const intFieldElement = document.getElementById(`int_field_${index}`);
            const intLabelElement = document.getElementById(`int_label_${index}`);

            if (intGroupElement) {
                intGroupElement.style.display = 'block';
            }

            if (intElement) {
                intElement.value = intField.value;
            }

            if (intFieldElement) {
                intFieldElement.value = intField.key;
            }

            // 根据字段类型设置标题
            if (intLabelElement) {
                if (intField.key.includes('SDXLEmptyLatentSizePicker+.batch_size')) {
                    intLabelElement.textContent = '整数参数（生成批次数）';
                } else if (intField.key.includes('PrimitiveInt.value')) {
                    intLabelElement.textContent = '整数参数（最大像素）';
                } else if (intField.key.includes('KSampler.steps')) {
                    intLabelElement.textContent = '整数参数（生成步数）';
                } else if (intField.key.includes('EmptySD3LatentImage.width')) {
                    intLabelElement.textContent = '整数参数（宽度）';
                } else if (intField.key.includes('EmptySD3LatentImage.height')) {
                    intLabelElement.textContent = '整数参数（高度）';
                } else if (intField.key.includes('EmptySD3LatentImage.batch_size')) {
                    intLabelElement.textContent = '整数参数（批次）';
                } else {
                    intLabelElement.textContent = '整数参数';
                }
            }

            console.log(`已应用整数参数 ${index}: ${intField.key} = ${intField.value}`);
        });
    }

    // 处理其他参数类型
    for (const [key, value] of Object.entries(currentConfigData.input_values)) {
        // 跳过已处理的字段
        if (processedFields.has(key)) continue;

        // 处理图片URL
        if (value && typeof value === 'string' && (value.startsWith('http') || value.startsWith('data:image'))) {
            // 查找对应的图片字段并填充URL
            for (let i = 1; i <= 5; i++) {
                const imageFieldElement = document.getElementById(`image_${i}_field`);
                const imageUrlElement = document.getElementById(`image_url_${i}`);

                if (imageFieldElement && imageUrlElement && imageFieldElement.value) {
                    const fieldName = imageFieldElement.value.split(':')[1];
                    if (fieldName && key.includes(fieldName)) {
                        imageUrlElement.value = value;
                        processedFields.add(key);
                        console.log(`填充图片 ${i} URL: ${value}`);
                        break;
                    }
                }
            }
        }
    }

    // 清空未被填充的图片URL输入框
    for (let i = 1; i <= 5; i++) {
        const imageUrlElement = document.getElementById(`image_url_${i}`);
        if (imageUrlElement) {
            imageUrlElement.value = ''; // 确保URL输入框为空，等待用户输入
        }
    }

    console.log('表单字段更新完成');
    console.log('处理的字段数量:', processedFields.size);
}

function isNumeric(str) {
    if (typeof str != "string") return false
    return !isNaN(str) && !isNaN(parseFloat(str))
}

// 侧边栏切换
function toggleSidebar() {
    if (document.getElementById('sidebar').classList.contains('w-64')) {
        collapseSidebar();
        localStorage.setItem('sidebar_state', 'collapsed');
    } else {
        expandSidebar();
        localStorage.setItem('sidebar_state', 'expanded');
    }
}

function collapseSidebar() {
    const sidebar = document.getElementById('sidebar');
    const main = document.querySelector('main');
    const toggleBtn = document.getElementById('sidebarToggleBtn');
    sidebar.classList.remove('w-64');
    sidebar.classList.add('w-16');
    main.classList.remove('ml-64');
    main.classList.add('ml-16');
    toggleBtn.classList.remove('hidden');
    sidebar.querySelectorAll('span').forEach(el => el.classList.add('hidden'));
}

function expandSidebar() {
    const sidebar = document.getElementById('sidebar');
    const main = document.querySelector('main');
    const toggleBtn = document.getElementById('sidebarToggleBtn');
    sidebar.classList.remove('w-16');
    sidebar.classList.add('w-64');
    main.classList.remove('ml-16');
    main.classList.add('ml-64');
    toggleBtn.classList.add('hidden');
    sidebar.querySelectorAll('span').forEach(el => el.classList.remove('hidden'));
}

// 图片预览函数
function previewImageBizy(event, previewId) {
    const file = event.target.files[0];
    if (!file) return;
    const previewContainer = document.getElementById(previewId);
    const previewImg = previewContainer.querySelector('img');
    const reader = new FileReader();
    reader.onload = function(e) {
        previewImg.src = e.target.result;
        previewContainer.classList.remove('hidden');
    }
    reader.readAsDataURL(file);
}

// 删除图片预览
function removeImagePreview(imageNum) {
    const previewContainer = document.getElementById(`preview${imageNum}`);
    const fileInput = document.getElementById(`image_${imageNum}`);
    previewContainer.classList.add('hidden');
    previewContainer.querySelector('img').src = '';
    fileInput.value = '';
}

// 配置开关功能初始化
function initConfigToggle() {
    const toggleBtn = document.getElementById('toggleConfigBtn');
    const toggleIcon = document.getElementById('toggleIcon');
    const toggleText = document.getElementById('toggleText');
    const apiConfigSection = document.getElementById('apiConfigSection');
    const inputParamsSection = document.getElementById('inputParamsSection');

    // 从localStorage读取保存的状态，默认为开启（显示）
    const savedState = localStorage.getItem('configToggleState');
    const isInitiallyVisible = savedState === 'hidden' ? false : true;

    // 初始化状态
    updateToggleState(isInitiallyVisible);

    // 添加点击事件监听器
    toggleBtn.addEventListener('click', function() {
        const fieldMappingInputs = document.querySelectorAll('.field-mapping-input');
        const firstFieldMappingVisible = fieldMappingInputs.length > 0 && fieldMappingInputs[0].style.display !== 'none';
        const newState = !firstFieldMappingVisible;

        updateToggleState(newState);
        localStorage.setItem('configToggleState', newState ? 'visible' : 'hidden');
    });
}

// 更新开关状态
function updateToggleState(isVisible) {
    const toggleIcon = document.getElementById('toggleIcon');
    const toggleText = document.getElementById('toggleText');
    const apiConfigSection = document.getElementById('apiConfigSection');
    const fieldMappingLabels = document.querySelectorAll('.field-mapping-label');
    const fieldMappingInputs = document.querySelectorAll('.field-mapping-input');

    if (isVisible) {
        // 显示配置
        apiConfigSection.style.display = 'grid';
        // 显示所有字段映射
        fieldMappingLabels.forEach(label => label.style.display = 'block');
        fieldMappingInputs.forEach(input => input.style.display = 'block');
        toggleIcon.className = 'fa fa-eye text-primary';
        toggleText.textContent = '隐藏配置';
    } else {
        // 隐藏配置
        apiConfigSection.style.display = 'none';
        // 隐藏所有字段映射
        fieldMappingLabels.forEach(label => label.style.display = 'none');
        fieldMappingInputs.forEach(input => input.style.display = 'none');
        toggleIcon.className = 'fa fa-eye-slash text-primary';
        toggleText.textContent = '显示配置';
    }
}

// 初始化CSV提示词选择功能
function initPromptSelector() {
    // 这些变量需要从PHP传递到JavaScript
    // 在实际应用中，应该在页面中定义这些变量为JavaScript变量
    const stylesData = window.stylesData || [];
    const templateData = window.templateData || [];

    const styleSelector = document.getElementById('styleSelector');
    const usePromptBtn = document.getElementById('usePromptBtn');
    const remarkSection = document.getElementById('remarkSection');
    const remarkText = document.getElementById('remarkText');
    const remarkImageContainer = document.getElementById('remarkImageContainer');
    const remarkImage = document.getElementById('remarkImage');

    if (!styleSelector || !usePromptBtn) return;

    // 下拉菜单选择事件
    styleSelector.addEventListener('change', function() {
        const selectedIndex = parseInt(this.value);
        if (isNaN(selectedIndex) || !stylesData[selectedIndex]) {
            // 隐藏说明区域
            remarkSection.classList.add('hidden');
            return;
        }

        const selectedStyle = stylesData[selectedIndex];

        // 显示说明文本
        if (selectedStyle.remark) {
            remarkText.textContent = selectedStyle.remark;

            // 检查是否包含图片URL
            const urlMatch = selectedStyle.remark.match(/(https?:\/\/[^\s]+)/);
            if (urlMatch) {
                const imageUrl = urlMatch[1];
                remarkImage.src = imageUrl;
                remarkImageContainer.classList.remove('hidden');

                // 图片加载错误处理
                remarkImage.onerror = function() {
                    remarkImageContainer.classList.add('hidden');
                };
            } else {
                remarkImageContainer.classList.add('hidden');
            }
        } else {
            remarkText.textContent = '暂无说明';
            remarkImageContainer.classList.add('hidden');
        }

        // 显示说明区域
        remarkSection.classList.remove('hidden');
    });

    // 提示词使用按钮点击事件
    usePromptBtn.addEventListener('click', function() {
        const selectedIndex = parseInt(styleSelector.value);
        if (isNaN(selectedIndex) || !stylesData[selectedIndex]) {
            showMessage('请先选择一个提示词模板', 'warning');
            return;
        }

        const selectedStyle = stylesData[selectedIndex];

        // 填充文本提示词
        const textPromptElement = document.getElementById('text_prompt');
        if (textPromptElement && selectedStyle.prompt) {
            textPromptElement.value = selectedStyle.prompt;

            // 触发change事件，以便其他可能的监听器能够响应
            const event = new Event('change', { bubbles: true });
            textPromptElement.dispatchEvent(event);

            showMessage(`已使用提示词模板："${selectedStyle.name}"`, 'success');
        } else {
            showMessage('无法找到文本提示词输入框', 'error');
        }
    });
}

// 显示消息函数（简单实现）
function showMessage(message, type = 'info') {
    // 创建消息元素
    const messageDiv = document.createElement('div');
    messageDiv.className = `fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg z-50 transition-all duration-300 flex items-center space-x-2`;

    // 根据类型设置样式
    switch(type) {
        case 'success':
            messageDiv.className += ' bg-green-500 text-white';
            messageDiv.innerHTML = `<i class="fa fa-check-circle"></i><span>${message}</span>`;
            break;
        case 'warning':
            messageDiv.className += ' bg-yellow-500 text-white';
            messageDiv.innerHTML = `<i class="fa fa-exclamation-triangle"></i><span>${message}</span>`;
            break;
        case 'error':
            messageDiv.className += ' bg-red-500 text-white';
            messageDiv.innerHTML = `<i class="fa fa-times-circle"></i><span>${message}</span>`;
            break;
        default:
            messageDiv.className += ' bg-blue-500 text-white';
            messageDiv.innerHTML = `<i class="fa fa-info-circle"></i><span>${message}</span>`;
    }

    // 添加到页面
    document.body.appendChild(messageDiv);

    // 3秒后自动移除
    setTimeout(() => {
        messageDiv.style.opacity = '0';
        setTimeout(() => {
            if (messageDiv.parentNode) {
                messageDiv.parentNode.removeChild(messageDiv);
            }
        }, 300);
    }, 3000);
}

// 打开模板展示弹出窗口
function openTemplateModal() {
    // 这些变量需要从PHP传递到JavaScript
    // 在实际应用中，应该在页面中定义这些变量为JavaScript变量
    const templateData = window.templateData || [];
    
    const modal = document.getElementById('templateModal');
    const grid = document.getElementById('templateGrid');

    // 清空现有内容
    grid.innerHTML = '';

    // 生成模板卡片
    templateData.forEach(template => {
        const card = document.createElement('div');
        card.className = 'rounded-lg overflow-hidden shadow-md hover:shadow-lg transition-all duration-300 transform hover:scale-105';

        const imageUrl = template.url_images || 'https://via.placeholder.com/300x200?text=No+Image';
        const templateName = template.name || 'Unknown Template';
        const webAppId = template.web_app_id || 'N/A';
        const templateId = template.id || 'N/A';

        const infoContent = template.info || '暂无描述';
        card.innerHTML = `
            <div class="relative h-80 group cursor-pointer">
                <!-- 背景图片 -->
                <img src="${imageUrl}" alt="${templateName}"
                     class="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
                     onerror="this.src='https://via.placeholder.com/300x320?text=Image+Error'">

                <!-- 渐变遮罩层 -->
                <div class="absolute inset-0 bg-gradient-to-t from-black/80 via-black/40 to-transparent"></div>

                <!-- 左上角：web_app_id -->
                <div class="absolute top-2 left-2 bg-orange-500 text-white px-2 py-1 rounded text-xs font-semibold">
                    App: ${webAppId}
                </div>

                <!-- 右上角：模板ID -->
                <div class="absolute top-2 right-2 bg-black bg-opacity-70 text-white px-2 py-1 rounded text-xs font-semibold">
                    ID: ${templateId}
                </div>

                <!-- 底部悬浮文字信息 -->
                <div class="absolute bottom-0 left-0 right-0 p-4 text-white">
                    <h3 class="font-bold text-lg mb-1 line-clamp-2 drop-shadow-lg">${templateName}</h3>
                    <p class="text-sm opacity-90 line-clamp-2 drop-shadow-md">${infoContent}</p>
                </div>
            </div>
        `;

        // 点击事件：跳转到模板页面
        card.addEventListener('click', function() {
            // 获取登录参数
            const loginParam = getCookie('enorg') || 'ph';
            const url = `?login=${loginParam}&id=${templateId}`;
            window.location.href = url;
        });

        grid.appendChild(card);
    });

    // 显示弹出窗口
    modal.classList.remove('hidden');
    document.body.style.overflow = 'hidden';
}

// 关闭模板展示弹出窗口
function closeTemplateModal() {
    const modal = document.getElementById('templateModal');
    modal.classList.add('hidden');
    document.body.style.overflow = 'auto';
}

// 点击背景关闭弹出窗口
document.addEventListener('click', function(event) {
    const modal = document.getElementById('templateModal');
    if (event.target === modal) {
        closeTemplateModal();
    }
});

// ESC键关闭弹出窗口
document.addEventListener('keydown', function(event) {
    if (event.key === 'Escape') {
        closeTemplateModal();
    }
});

// 获取Cookie值的辅助函数
function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(';').shift();
}

// 图片轮播功能
let currentImageIndex = 0;
const carouselItems = document.querySelectorAll('.carousel-item');

// 显示指定索引的图片
function showImage(index) {
    // 隐藏所有图片
    carouselItems.forEach(item => item.classList.add('hidden'));
    
    // 显示指定图片
    if (carouselItems[index]) {
        carouselItems[index].classList.remove('hidden');
        currentImageIndex = index;
        
        // 更新指示器
        updateIndicators();
    }
}

// 更新指示器状态
function updateIndicators() {
    const indicators = document.querySelectorAll('#imageCarousel + div button');
    indicators.forEach((indicator, index) => {
        if (index === currentImageIndex) {
            indicator.classList.remove('bg-white/50');
            indicator.classList.add('bg-white');
        } else {
            indicator.classList.remove('bg-white');
            indicator.classList.add('bg-white/50');
        }
    });
}

// 显示下一张图片
function nextImage() {
    const totalImages = carouselItems.length;
    const nextIndex = (currentImageIndex + 1) % totalImages;
    showImage(nextIndex);
}

// 显示上一张图片
function prevImage() {
    const totalImages = carouselItems.length;
    const prevIndex = (currentImageIndex - 1 + totalImages) % totalImages;
    showImage(prevIndex);
}

// 自动轮播（可选）
/*
setInterval(() => {
    nextImage();
}, 5000); // 每5秒切换一次
*/
